<template>
  <div id="userManagePage">
    <a-form layout="inline" :model="searchParams" @finish="doSearch">
      <a-form-item label="账号">
        <a-input v-model:value="searchParams.userAccount" placeholder="输入账号" />
      </a-form-item>
      <a-form-item label="用户名">
        <a-input v-model:value="searchParams.userName" placeholder="输入用户名" />
      </a-form-item>
      <a-form-item>
        <a-button type="primary" html-type="submit">搜索</a-button>
      </a-form-item>
    </a-form>

    <div style="margin-bottom: 16px"></div>
    <a-table
      :columns="columns"
      :data-source="dataList"
      :pagination="pagination"
      @change="doTableChange"
    >
      <template #headerCell="{ column }">
        <template v-if="column.key === 'name'">
          <span>
            <smile-outlined />
            Name
          </span>
        </template>
      </template>

      <template #bodyCell="{ column, record }">
        <template v-if="column.dataIndex === 'userAvatar'">
          <a-image :src="record.userAvatar" :width="120" />
        </template>
        <template v-else-if="column.dataIndex === 'userRole'">
          <a-tag :color="getRoleColor(record.userRole)">{{ getRoleText(record.userRole) }}</a-tag>
        </template>
        <template v-else-if="column.dataIndex === 'createTime'">
          {{ dayjs(record.createTime).format('YYYY-MM-DD HH:mm:ss') }}
        </template>
        <template v-else-if="column.dataIndex === 'updateTime'">
          {{ dayjs(record.updateTime).format('YYYY-MM-DD HH:mm:ss') }}
        </template>

        <template v-else-if="column.key === 'action'">
          <a-space>
            <a-button type="primary" @click="showEditModal(record)">编辑</a-button>
            <a-button
              v-if="record.userRole !== 'admin'"
              :class="record.userRole === 'ban' ? 'unfreeze-button' : 'freeze-button'"
              @click="handleFreezeUser(record)"
            >
              {{ record.userRole === 'ban' ? '解冻' : '冻结' }}
            </a-button>
            <a-button
              type="primary"
              style="background-color: #52c41a; border-color: #52c41a"
              @click="handleResetPassword(record)"
              >重置密码
            </a-button>
          </a-space>
        </template>
      </template>
    </a-table>

    <!-- 编辑用户弹窗 -->
    <a-modal
      v-model:visible="editModalVisible"
      title="编辑用户"
      @ok="handleEditSubmit"
      @cancel="editModalVisible = false"
    >
      <a-form :model="editForm" layout="vertical">
        <a-form-item label="用户名" required>
          <a-input v-model:value="editForm.userName" placeholder="请输入用户名" />
        </a-form-item>
        <a-form-item label="个人简介">
          <a-textarea v-model:value="editForm.userProfile" placeholder="请输入个人简介" :rows="4" />
        </a-form-item>
        <a-form-item label="用户角色" required>
          <a-select v-model:value="editForm.userRole">
            <a-select-option value="admin">管理员</a-select-option>
            <a-select-option value="user">普通用户</a-select-option>
            <a-select-option value="ban">已冻结</a-select-option>
          </a-select>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { computed, createVNode, onMounted, reactive, ref } from 'vue'
import { message, Modal } from 'ant-design-vue'
import dayjs from 'dayjs'
import {
  listUserByPageUsingPost,
  resetPasswordUsingGet,
  updateUserUsingPost,
} from '@/api/userController'
import { ExclamationCircleOutlined } from '@ant-design/icons-vue'

// 编辑弹窗相关
const editModalVisible = ref(false)
const editForm = reactive<API.UserUpdateRequest>({
  id: undefined,
  userName: '',
  userProfile: '',
  userRole: '',
  userAvatar: '',
})

const columns = [
  {
    title: 'id',
    dataIndex: 'id',
    align: 'center',
  },
  {
    title: '账号',
    dataIndex: 'userAccount',
    align: 'center',
  },
  {
    title: '用户名',
    dataIndex: 'userName',
    align: 'center',
  },
  {
    title: '头像',
    dataIndex: 'userAvatar',
    align: 'center',
  },
  {
    title: '简介',
    dataIndex: 'userProfile',
    align: 'center',
  },
  {
    title: '用户角色',
    dataIndex: 'userRole',
    align: 'center',
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    align: 'center',
  },
  {
    title: '更新时间',
    dataIndex: 'updateTime',
    align: 'center',
  },
  {
    title: '操作',
    key: 'action',
    width: 280,
    align: 'center',
  },
]

// 获取角色文本
const getRoleText = (role: string) => {
  const roleMap: Record<string, string> = {
    admin: '管理员',
    user: '普通用户',
    ban: '已冻结',
  }
  return roleMap[role] || role
}

// 获取角色标签颜色
const getRoleColor = (role: string) => {
  const colorMap: Record<string, string> = {
    admin: 'green',
    user: 'blue',
    ban: 'red',
  }
  return colorMap[role] || 'default'
}

// 数据
const dataList = ref<API.User[]>([])
const total = ref(0)

// 搜索条件
const searchParams = reactive<API.UserQueryRequest>({
  current: 1,
  pageSize: 10,
})

// 获取数据
const fetchData = async () => {
  const res = await listUserByPageUsingPost(searchParams)
  if (res.data.data) {
    dataList.value = res.data.data.records ?? []
    total.value = res.data.data.total ?? 0
  } else {
    message.error('获取数据失败，' + res.data.message)
  }
}

// 页面加载时请求一次
onMounted(() => {
  fetchData()
})

// 分页参数
const pagination = computed(() => {
  return {
    current: searchParams.current ?? 1,
    pageSize: searchParams.pageSize ?? 10,
    total: total.value,
    showSizeChanger: true,
    showTotal: (totalCount: number) => `共 ${totalCount} 条`,
  }
})

// 表格变化处理
const doTableChange = (page: any) => {
  searchParams.current = page.current
  searchParams.pageSize = page.pageSize
  fetchData()
}

// 获取数据
const doSearch = () => {
  // 重置页码
  searchParams.current = 1
  fetchData()
}

// 显示编辑弹窗
const showEditModal = (record: API.UserVO) => {
  editForm.id = record.id
  editForm.userName = record.userName
  editForm.userProfile = record.userProfile
  editForm.userRole = record.userRole
  editForm.userAvatar = record.userAvatar
  editModalVisible.value = true
}

// 处理编辑提交
const handleEditSubmit = async () => {
  if (!editForm.userName?.trim()) {
    message.warning('请输入用户名')
    return
  }
  if (!editForm.userRole) {
    message.warning('请选择用户角色')
    return
  }

  try {
    const res = await updateUserUsingPost(editForm)
    if (res.data.code === 0) {
      message.success('更新成功')
      editModalVisible.value = false
      fetchData()
    } else {
      message.error('更新失败：' + res.data.message)
    }
  } catch (error: any) {
    message.error('更新失败：' + error.message)
  }
}

// 处理冻结/解冻用户
const handleFreezeUser = (record: API.UserVO) => {
  const isBanned = record.userRole === 'ban'
  const title = isBanned ? '确认解冻用户？' : '确认冻结用户？'
  const content = isBanned ? '解冻后用户将恢复正常使用权限' : '冻结后用户将无法使用系统功能'

  Modal.confirm({
    title,
    content,
    icon: createVNode(ExclamationCircleOutlined),
    okText: '确认',
    cancelText: '取消',
    async onOk() {
      try {
        const res = await updateUserUsingPost({
          id: record.id,
          userRole: isBanned ? 'user' : 'ban',
        })
        if (res.data.code === 0) {
          message.success(isBanned ? '解冻成功' : '冻结成功')
          fetchData()
        } else {
          message.error('操作失败：' + res.data.message)
        }
      } catch (error: any) {
        message.error('操作失败：' + error.message)
      }
    },
  })
}

// 处理重置密码
const handleResetPassword = (record: API.UserVO) => {
  Modal.confirm({
    title: '确认重置密码？',
    content: '重置后密码将变为默认密码',
    icon: createVNode(ExclamationCircleOutlined),
    okText: '确认',
    cancelText: '取消',
    async onOk() {
      try {
        const res = await resetPasswordUsingGet({ id: record.id })
        if (res.data.code === 0) {
          message.success('密码重置成功')
        } else {
          message.error('重置失败：' + res.data.message)
        }
      } catch (error: any) {
        message.error('重置失败：' + error.message)
      }
    },
  })
}
</script>

<style scoped>
#userManagePage {
  padding: 24px;
}

.freeze-button {
  background-color: #ff4d4f;
  border-color: #ff4d4f;
  color: #fff;
}

.freeze-button:hover {
  background-color: #ff7875 !important;
  border-color: #ff7875 !important;
  color: #fff !important;
}

.unfreeze-button {
  background-color: #faad14;
  border-color: #faad14;
  color: #fff;
}

.unfreeze-button:hover {
  background-color: #ffc53d !important;
  border-color: #ffc53d !important;
  color: #fff !important;
}
</style>
